from flask import request, jsonify, g

from . import index_blue
from first_info.models import User, News, Category
from flask import render_template, current_app
from first_info import constants, response_code
from first_info.utils.comment import user_login_data

@index_blue.route('/news_list')
def news_list():
    # 1. 获取参数
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")
    # 2.校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.PARAMERR, errmag='参数错误')
    # 3.查询数据库,当是最新时，不过滤分类
    try:
        if cid == 1:
            paginate = News.query.filter(News.status == 0).order_by(News.create_time.desc()).paginate(page, per_page, False)

        else:
            paginate = News.query.filter(News.status == 0, News.category_id == cid).order_by(News.create_time.desc()).paginate(page, per_page, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmag='查询数据库错误')

    #  4.提供参数
    else:
        # 4.1返回的数据结果对象
        items = paginate.items

        # 4.2 总页数
        total_page = paginate.pages
        # 4.3当前第几页
        current_page = paginate.page
    news_list = []
    for news in items:
        news_list.append(news.to_basic_dict())

    data = {
        "news_list": news_list,
        "total_page": total_page,
        "current_page": current_page

    }
    #  5.返回参数
    return jsonify(errno=response_code.RET.OK, errmag='成功', data=data)



@index_blue.route('/')
@user_login_data
def index():
    # 1.判断用户是否有进行状态保持，获取session成功，显示名称，反之，显示注册，登陆
    # 使用装饰器进行装饰
    user = g.user
    # 2.查询数据库更加news的点击量clicks进行倒序
    news_clicks = None
    try:
        news_clicks = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 3.查询新闻分类
    try:
        categories = Category.query.all()
        print(categories)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmag='数据库查询错误')
    categorys = []
    for category in categories:
        categorys.append(category.to_dict())
    print(categorys)

    content = {
        'user': user.to_dict() if user else None,
        'news_clicks': news_clicks,
        'categorys': categorys
    }

    return render_template('news/index.html', **content)

@index_blue.route('/favicon.ico', methods=['GET'])
def favicon():
    # result = open('/home/python/Desktop/object/huangli/bigbigbong/first_info/static/news/favicon.ico', 'rb')
    #
    # return result.read()
    return current_app.send_static_file('news/favicon.ico')

